package com.jn.erp.web.api.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jn.erp.common.annotation.Log;
import com.jn.erp.common.core.page.TableDataInfo;
import com.jn.erp.common.core.result.AjaxResult;
import com.jn.erp.common.enums.BusinessType;
import com.jn.erp.common.exception.ServiceException;
import com.jn.erp.common.utils.StringUtils;
import com.jn.erp.security.controller.BaseWebAuthController;
import com.jn.erp.security.entity.SysRole;
import com.jn.erp.security.entity.SysUser;
import com.jn.erp.security.entity.SysUserRole;
import com.jn.erp.security.sysservice.SysRoleService;
import com.jn.erp.security.sysservice.SysUserRoleService;
import com.jn.erp.security.sysservice.SysUserService;
import com.jn.erp.security.utils.SecurityUtils;
import com.jn.erp.web.api.sys.entity.SysOrg;
import com.jn.erp.web.api.sys.entity.SysOrgUser;
import com.jn.erp.web.api.sys.service.SysOrgService;
import com.jn.erp.web.api.sys.service.SysOrgUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/8/30 10:13
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseWebAuthController {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;


    @Autowired
    private com.jn.erp.web.api.student.service.StudentService studentService;

    @Autowired
    private SysOrgUserService sysOrgUserService;

    /**
     * 获取部门树列表(超管用户使用，能看全部)
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/orgTree")
    public AjaxResult orgTree(SysOrg sysorg) {
        QueryWrapper<SysOrg> qw = new QueryWrapper<>();
        qw.eq("deleted", "0");
        List<SysOrg> list = sysOrgService.list(qw);
        return success(sysOrgService.buildDeptTreeSelect(list));
    }

    /**
     * 获取用户列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = sysUserService.selectUserList(user);
        return getDataTable(list);
    }


    /**
     * 新增用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "系统新增用户", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@Validated @RequestBody SysUser user) {
//        deptService.checkDeptDataScope(user.getDeptId());
//        roleService.checkRoleDataScope(user.getRoleIds());
        if (!sysUserService.checkUserNameUnique(user)) {
//            //如果在其他机构存在，那么提示更新
//            boolean b = sysUserService.checkUserNameDept(user);
//            if (!b) {
//                return error("checkUserNameDept");
//            }
            return error("新增用户'" + user.getName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getMobile()) && !sysUserService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !sysUserService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getName() + "'失败，邮箱账号已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setAddTime(LocalDateTime.now());
        sysUserService.save(user);
        SysOrgUser sysOrgUser = new SysOrgUser();
        sysOrgUser.setOrgId(user.getOrgId());
        sysOrgUser.setUserId(user.getId());
        if(getUserId()==1L){
            sysOrgUser.setNickName("运维新建用户");
        }
        sysOrgUserService.save(sysOrgUser);
        sysUserRoleService.insertUserRole(user.getId(), user.getRoleIds(),user.getOrgId());
        return toAjax(true);
    }


    /**
     * 根据用户编号获取详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
//        sysUserService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = sysRoleService.list();
//        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("roles", roles);
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = sysUserService.getById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            QueryWrapper<SysUserRole> qw = new QueryWrapper<>();
            qw.eq("user_id", sysUser.getId());
            List<SysUserRole> list = sysUserRoleService.list(qw);
            ajax.put("roleIds", list.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }


    /**
     * 获取角色
     */
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = "/getRoles")
    public AjaxResult getRoles(SysUser user) {
//        SysRoleVo role = new SysRoleVo();
        Long deptIdParam = user.getOrgId();
//        role.setDeptId(Long.valueOf(deptIdParam));
        QueryWrapper<SysRole> qw = new QueryWrapper<>();
        qw.in("org_id", Arrays.asList(1L, deptIdParam));
        List<SysRole> roles = sysRoleService.list(qw);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("roles", roles);
        return ajax;
    }

    /**
     * 修改用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "系统修改用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
//        sysUserService.checkUserAllowed(user);
//        userService.checkUserDataScope(user.getUserId());
//        deptService.checkDeptDataScope(user.getDeptId());
//        roleService.checkRoleDataScope(user.getRoleIds());
        if (user.getId() != null && 1L == user.getId()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
        if (!sysUserService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getName()) && !sysUserService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !sysUserService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getName() + "'失败，邮箱账号已存在");
        }
        Long userId = user.getId();
        // 删除用户与角色关联
        QueryWrapper<SysUserRole> qwd = new QueryWrapper<>();
        qwd.eq("user_id", userId);
        sysUserRoleService.remove(qwd);
        // 新增用户与角色管理
        sysUserRoleService.insertUserRole(userId, user.getRoleIds(),user.getOrgId());
        return toAjax(sysUserService.updateById(user));
    }

    /**
     * 状态修改
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "系统用户状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        if (user.getId() != null && 1L == user.getId()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
//        sysUserService.checkUserDataScope(user.getUserId());
        UpdateWrapper<SysUser> uw = new UpdateWrapper<>();
        uw.set("state", user.getState());
        uw.eq("id", user.getId());
        sysUserService.update(uw);
        return toAjax(true);
    }


    /**
     * 删除用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "系统删除用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        List<Long> longs = Arrays.asList(userIds);
        for (Long userId : longs) {
            if(userId==1l){
                longs.remove(userId);
            }
//            checkUserAllowed(new SysUser(userId));
//            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        QueryWrapper<SysUserRole> qwd = new QueryWrapper<>();
        qwd.in("user_id", userIds);
        sysUserRoleService.remove(qwd);
        sysUserService.removeByIds(longs);
        return toAjax(true);
    }


    /**
     * 重置密码
     */
//    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "系统重置用户密码", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        if (user.getId() != null && 1L == user.getId()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
//        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(sysUserService.updateById(user));
    }



//    /**
//     * 根据用户编号获取授权角色
//     */
////    @PreAuthorize("@ss.hasPermi('system:user:query')")
//    @GetMapping("/authRole/{userId}")
//    public AjaxResult authRole(@PathVariable("userId") Long userId) {
//        AjaxResult ajax = AjaxResult.success();
//        SysUser user = sysUserService.getById(userId);
//        QueryWrapper<SysUserRole> qw = new QueryWrapper<>();
//        qw.eq("user_id", userId);
//        List<SysUserRole> list = sysUserRoleService.list(qw);
//        List<Long> collect = list.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
//        QueryWrapper<SysRole> qwr=new QueryWrapper<>();
//        qwr.in("role_id",collect);
//        List<SysRole> roles = sysRoleService.list(qwr);
//        ajax.put("user", user);
//        ajax.put("roles", userId==1L ? roles : roles.stream().filter(r -> !(1L == r.getRoleId())).collect(Collectors.toList()));
//        return ajax;
//    }


}
